{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Source of the materials**: Biopython Tutorial and Cookbook (adapted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Sequence annotation objects"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The previous notebook introduced the sequence classes.  Immediately ``above'' the Seq class is the Sequence Record or SeqRecord class, defined in the Bio.SeqRecord module. This class allows higher level features such as identifiers and features (as SeqFeature objects) to be associated with the sequence, and is used throughout the sequence input/output interface Bio.SeqIO described fully in another notebook.\n",
    "\n",
    "If you are only going to be working with simple data like FASTA files, you can probably skip this chapter\n",
    "for now. If on the other hand you are going to be using richly annotated sequence data, say from GenBank\n",
    "or EMBL files, this information is quite important.\n",
    "\n",
    "While this chapter should cover most things to do with the \\verb|SeqRecord| and \\verb|SeqFeature| objects in this chapter, you may also want to read the SeqRecord wiki page (http://biopython.org/wiki/SeqRecord), and the built in documentation (also online -- http://biopython.org/DIST/docs/api/Bio.SeqRecord.SeqRecord-class.html - SeqRecord and http://biopython.org/DIST/docs/api/Bio.SeqFeature.SeqFeature-class.html - SeqFeature):\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from Bio import SeqIO, SeqFeature\n",
    "from Bio.Alphabet import SingleLetterAlphabet, generic_protein\n",
    "from Bio.Alphabet.IUPAC import IUPACAmbiguousDNA\n",
    "from Bio.SeqFeature import FeatureLocation\n",
    "from Bio.SeqRecord import SeqRecord"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The SeqRecord Object"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The SeqRecord (Sequence Record) class is defined in the Bio.SeqRecord module. This class allows higher level features such as identifiers and features to be associated with a sequence, and is the basic data type for the Bio.SeqIO sequence input/output interface.\n",
    "\n",
    "The SeqRecord class itself is quite simple, and offers the following information as attributes:\n",
    "\n",
    "*  **.seq** - The sequence itself, typically a Seq object.\n",
    "\n",
    "* **.id** - The primary ID used to identify the sequence - a string. In most cases this is something like an accession number.\n",
    "\n",
    "* **.name** - A 'common' name/id for the sequence - a string. In some cases this will be the same as the accession number, but it could also be a clone name. I think of this as being analogous to the LOCUS id in a GenBank record.\n",
    "\n",
    "* **.description** - A human readable description or expressive name for the sequence - a string.\n",
    "  \n",
    "* **.letter_annotations** - Holds per-letter-annotations using a (restricted) dictionary of additional information about the letters in the sequence. The keys are the name of the information, and the information is contained in the value as a Python sequence (i.e. a list, tuple or string) with the same length as the sequence itself.  This is often used for quality scores or secondary structure information (e.g. from Stockholm/PFAM alignment files).\n",
    "\n",
    "* **.annotations** - A dictionary of additional information about the sequence. The keys are the name of the information, and the information is contained in the value. This allows the addition of more 'unstructured' information to the sequence.\n",
    "  \n",
    "* **.features** - A list of SeqFeature objects with more structured information about the features on a sequence (e.g. position of genes on a genome, or domains on a protein sequence).\n",
    "  \n",
    "* **.dbxrefs** - A list of database cross-references as strings.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Creating a SeqRecord"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Using a SeqRecord object is not very complicated, since all of the\n",
    "information is presented as attributes of the class. Usually you won't create\n",
    "a SeqRecord 'by hand', but instead use Bio.SeqIO to read in a\n",
    "sequence file for you and the examples\n",
    "below).  However, creating SeqRecord can be quite simple."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### SeqRecord objects from scratch"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To create a SeqRecord at a minimum you just need a Seq object:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from Bio.Seq import Seq\n",
    "from Bio.SeqRecord import SeqRecord"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "GATC\n",
      "ID: <unknown id>\n",
      "Name: <unknown name>\n",
      "Description: <unknown description>\n",
      "Number of features: 0\n",
      "Seq('GATC', Alphabet())\n"
     ]
    }
   ],
   "source": [
    "simple_seq = Seq(\"GATC\")\n",
    "print(simple_seq)\n",
    "simple_seq_r = SeqRecord(simple_seq)\n",
    "print(simple_seq_r)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Additionally, you can also pass the id, name and description to the initialization function, but if not they will be set as strings indicating they are unknown, and can be modified subsequently:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Made up sequence I wish I could write a paper about\n",
      "GATC\n"
     ]
    }
   ],
   "source": [
    "simple_seq_r.id\n",
    "simple_seq_r.id = \"AC12345\"\n",
    "simple_seq_r.description = \"Made up sequence I wish I could write a paper about\"\n",
    "print(simple_seq_r.description)\n",
    "simple_seq_r.seq\n",
    "print(simple_seq_r.seq)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Including an identifier is very important if you want to output your SeqRecord to a file.  You would normally include this when creating the object:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "GATC\n",
      "ID: AC12345\n",
      "Name: <unknown name>\n",
      "Description: <unknown description>\n",
      "Number of features: 0\n",
      "Seq('GATC', Alphabet())\n"
     ]
    }
   ],
   "source": [
    "simple_seq = Seq(\"GATC\")\n",
    "print(simple_seq)\n",
    "simple_seq_r = SeqRecord(simple_seq, id=\"AC12345\")\n",
    "print(simple_seq_r)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As mentioned above, the SeqRecord has an dictionary attribute annotations. This is used\n",
    "for any miscellaneous annotations that doesn't fit under one of the other more specific attributes.\n",
    "Adding annotations is easy, and just involves dealing directly with the annotation dictionary:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'evidence': 'None. I just made it up.'}\n",
      "None. I just made it up.\n"
     ]
    }
   ],
   "source": [
    "simple_seq_r.annotations[\"evidence\"] = \"None. I just made it up.\"\n",
    "print(simple_seq_r.annotations)\n",
    "print(simple_seq_r.annotations[\"evidence\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Working with per-letter-annotations is similar, letter_annotations is a\n",
    "dictionary like attribute which will let you assign any Python sequence (i.e.\n",
    "a string, list or tuple) which has the same length as the sequence:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'phred_quality': [40, 40, 38, 30]}\n",
      "[40, 40, 38, 30]\n"
     ]
    }
   ],
   "source": [
    "simple_seq_r.letter_annotations[\"phred_quality\"] = [40, 40, 38, 30]\n",
    "print(simple_seq_r.letter_annotations)\n",
    "print(simple_seq_r.letter_annotations[\"phred_quality\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The dbxrefs and features attributes are just Python lists, and\n",
    "should be used to store strings and SeqFeature objects (discussed later) respectively."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### SeqRecord objects from FASTA files"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This example uses a fairly large FASTA file containing the whole sequence for \\textit{Yersinia pestis biovar Microtus} str. 91001 plasmid pPCP1, originally downloaded from the NCBI.  This file is included with the Biopython unit tests under the GenBank folder, or online (http://biopython.org/SRC/biopython/Tests/GenBank/NC_005816.fna) from our website.\n",
    "\n",
    "The file starts like this - and you can check there is only one record present (i.e. only one line starting with a greater than symbol):\n",
    "\n",
    "    >gi|45478711|ref|NC_005816.1| Yersinia pestis biovar Microtus ... pPCP1, complete sequence\n",
    "    TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGGGGGTAATCTGCTCTCC\n",
    "    ...\n",
    "\n",
    "In a previous notebook you will have seen the function Bio.SeqIO.parse\n",
    "used to loop over all the records in a file as SeqRecord objects. The Bio.SeqIO module\n",
    "has a sister function for use on files which contain just one record which we'll use here:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ID: gi|45478711|ref|NC_005816.1|\n",
      "Name: gi|45478711|ref|NC_005816.1|\n",
      "Description: gi|45478711|ref|NC_005816.1| Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence\n",
      "Number of features: 0\n",
      "Seq('TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGG...CTG', SingleLetterAlphabet())\n"
     ]
    }
   ],
   "source": [
    "record = SeqIO.read(\"data/NC_005816.fna\", \"fasta\")\n",
    "print(record)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, let's have a look at the key attributes of this SeqRecord\n",
    "individually - starting with the seq attribute which gives you a\n",
    "Seq object:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGG...CTG', SingleLetterAlphabet())"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "record.seq"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here Bio.SeqIO has defaulted to a generic alphabet, rather\n",
    "than guessing that this is DNA. If you know in advance what kind of sequence\n",
    "your FASTA file contains, you can tell Bio.SeqIO which alphabet to use.\n",
    "\n",
    "Next, the identifiers and description:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "gi|45478711|ref|NC_005816.1|\n",
      "gi|45478711|ref|NC_005816.1|\n",
      "gi|45478711|ref|NC_005816.1| Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence\n"
     ]
    }
   ],
   "source": [
    "print(record.id)\n",
    "print(record.name)\n",
    "print(record.description)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As you can see above, the first word of the FASTA record's title line (after\n",
    "removing the greater than symbol) is used for both the id and\n",
    "name attributes. The whole title line (after removing the greater than\n",
    "symbol) is used for the record description. This is deliberate, partly for\n",
    "backwards compatibility reasons, but it also makes sense if you have a FASTA\n",
    "file like this:\n",
    "\n",
    "    >Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1\n",
    "    TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGGGGGTAATCTGCTCTCC\n",
    "    ...\n",
    "\n",
    "Note that none of the other annotation attributes get populated when reading a\n",
    "FASTA file:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[]\n",
      "{}\n",
      "{}\n",
      "[]\n"
     ]
    }
   ],
   "source": [
    "print(record.dbxrefs)\n",
    "print(record.annotations)\n",
    "print(record.letter_annotations)\n",
    "print(record.features)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this case our example FASTA file was from the NCBI, and they have a fairly well defined set of conventions for formatting their FASTA lines. This means it would be possible to parse this information and extract the GI number and accession for example. However, FASTA files from other sources vary, so this isn't possible in general.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### SeqRecord objects from GenBank files"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As in the previous example, we're going to look at the whole sequence for _Yersinia pestis biovar Microtus_ str. 91001 plasmid pPCP1, originally downloaded from the NCBI, but this time as a GenBank file.\n",
    "\n",
    "This file contains a single record (i.e. only one LOCUS line) and starts:\n",
    "\n",
    "    LOCUS       NC_005816               9609 bp    DNA     circular BCT 21-JUL-2008\n",
    "    DEFINITION  Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete\n",
    "                sequence.\n",
    "    ACCESSION   NC_005816\n",
    "    VERSION     NC_005816.1  GI:45478711\n",
    "    PROJECT     GenomeProject:10638\n",
    "    ...\n",
    "\n",
    "Again, we'll use Bio.SeqIO to read this file in, and the code is almost identical to that for used above for the FASTA file:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ID: NC_005816.1\n",
      "Name: NC_005816\n",
      "Description: Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.\n",
      "Database cross-references: Project:58037\n",
      "Number of features: 41\n",
      "/taxonomy=['Bacteria', 'Proteobacteria', 'Gammaproteobacteria', 'Enterobacteriales', 'Enterobacteriaceae', 'Yersinia']\n",
      "/comment=PROVISIONAL REFSEQ: This record has not yet been subject to final\n",
      "NCBI review. The reference sequence was derived from AE017046.\n",
      "COMPLETENESS: full length.\n",
      "/accessions=['NC_005816']\n",
      "/organism=Yersinia pestis biovar Microtus str. 91001\n",
      "/sequence_version=1\n",
      "/source=Yersinia pestis biovar Microtus str. 91001\n",
      "/data_file_division=BCT\n",
      "/keywords=['']\n",
      "/date=21-JUL-2008\n",
      "/gi=45478711\n",
      "/references=[Reference(title='Genetics of metabolic variations between Yersinia pestis biovars and the proposal of a new biovar, microtus', ...), Reference(title='Complete genome sequence of Yersinia pestis strain 91001, an isolate avirulent to humans', ...), Reference(title='Direct Submission', ...), Reference(title='Direct Submission', ...)]\n",
      "Seq('TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGG...CTG', IUPACAmbiguousDNA())\n"
     ]
    }
   ],
   "source": [
    "record = SeqIO.read(\"data/NC_005816.gb\", \"genbank\")\n",
    "print(record)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You should be able to spot some differences already! But taking the attributes individually,\n",
    "the sequence string is the same as before, but this time Bio.SeqIO has been able to automatically assign a more specific alphabet:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGG...CTG', IUPACAmbiguousDNA())"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "record.seq"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The name comes from the LOCUS line, while the \\verb|id| includes the version suffix.\n",
    "\n",
    "The description comes from the DEFINITION line:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "NC_005816.1\n",
      "NC_005816\n",
      "Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.\n"
     ]
    }
   ],
   "source": [
    "print(record.id)\n",
    "print(record.name)\n",
    "print(record.description)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "GenBank files don't have any per-letter annotations:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{}"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "record.letter_annotations"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Most of the annotations information gets recorded in the \\verb|annotations| dictionary, for example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "11\n",
      "Yersinia pestis biovar Microtus str. 91001\n"
     ]
    }
   ],
   "source": [
    "print(len(record.annotations))\n",
    "print(record.annotations[\"source\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The dbxrefs list gets populated from any PROJECT or DBLINK lines:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['Project:58037']"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "record.dbxrefs"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, and perhaps most interestingly, all the entries in the features table (e.g. the genes or CDS features) get recorded as SeqFeature objects in the features list."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "41"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(record.features)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Feature, location and position objects"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### SeqFeature objects"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Sequence features are an essential part of describing a sequence. Once you get beyond the sequence itself, you need some way to organize and easily get at the more 'abstract' information that is known about the sequence. While it is probably impossible to develop a general sequence feature class that will cover everything, the Biopython SeqFeature class attempts to encapsulate as much of the information about the sequence as possible. The design is heavily based on the GenBank/EMBL feature tables, so if you understand how they look, you'll probably have an easier time grasping the structure of the Biopython classes.\n",
    "\n",
    "The key idea about each SeqFeature object is to describe a region on a parent sequence, typically a SeqRecord object. That region is described with a location object, typically a range between two positions (see below).\n",
    "\n",
    "The SeqFeature class has a number of attributes, so first we'll list them and their general features, and then later in the chapter work through examples to show how this applies to a real life example. The attributes of a SeqFeature are:\n",
    "\n",
    "*  **.type]** - This is a textual description of the type of feature (for instance, this will be something like 'CDS' or 'gene').\n",
    "\n",
    "* **.location** - The location of the SeqFeature on the sequence\n",
    "  that you are dealing with. The\n",
    "  SeqFeature delegates much of its functionality to the location\n",
    "  object, and includes a number of shortcut attributes for properties\n",
    "  of the location:\n",
    "\n",
    "  * **.ref** - shorthand for .location.ref - any (different)\n",
    "    reference sequence the location is referring to. Usually just None.\n",
    "\n",
    "  * **.ref_db** - shorthand for .location.ref_db - specifies\n",
    "    the database any identifier in .ref refers to. Usually just None.\n",
    "\n",
    "  * **.strand** - shorthand for .location.strand - the strand on\n",
    "    the sequence that the feature is located on. For double stranded nucleotide\n",
    "    sequence this may either be 1 for the top strand, -1 for the bottom\n",
    "    strand, 0 if the strand is important but is unknown, or None\n",
    "    if it doesn't matter. This is None for proteins, or single stranded sequences.\n",
    "\n",
    "* **.qualifiers** - This is a Python dictionary of additional information about the feature. The key is some kind of terse one-word description of what the information contained in the value is about, and the value is the actual information. For example, a common key for a qualifier might be 'evidence' and the value might be 'computational (non-experimental). This is just a way to let the person who is looking at the feature know that it has not be experimentally (i.e. in a wet lab) confirmed. Note that other the value will be a list of strings (even when there is only one string). This is a reflection of the feature tables in GenBank/EMBL files.\n",
    " \n",
    "* **.sub_features** - This used to be used to represent features with complicated locations like 'joins' in GenBank/EMBL files. This has been deprecated with the introduction of the CompoundLocation object, and should now be ignored."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Positions and locations"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The key idea about each SeqFeature object is to describe a\n",
    "region on a parent sequence, for which we use a location object,\n",
    "typically describing a range between two positions. Two try to\n",
    "clarify the terminology we're using:\n",
    "\n",
    "*  **position** - This refers to a single position on a sequence,\n",
    "  which may be fuzzy or not. For instance, 5, 20, \\<100 and\n",
    "  \\>200 are all positions.\n",
    "\n",
    "* **location** - A location is region of sequence bounded by\n",
    "  some positions. For instance 5..20 (i.e. 5 to 20) is a location.\n",
    "\n",
    "I just mention this because sometimes I get confused between the two."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### FeatureLocation object"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Unless you work with eukaryotic genes, most SeqFeature locations are\n",
    "extremely simple - you just need start and end coordinates and a strand.\n",
    "That's essentially all the basic FeatureLocation object does.\n",
    "\n",
    "In practise of course, things can be more complicated. First of all\n",
    "we have to handle compound locations made up of several regions.\n",
    "Secondly, the positions themselves may be fuzzy (inexact)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### CompoundLocation object"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Biopython 1.62 introduced the CompoundLocation as part of\n",
    "a restructuring of how complex locations made up of multiple regions\n",
    "are represented.\n",
    "The main usage is for handling `join' locations in EMBL/GenBank files.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Fuzzy Positions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So far we've only used simple positions. One complication in dealing\n",
    "with feature locations comes in the positions themselves.\n",
    "In biology many times things aren't entirely certain\n",
    "(as much as us wet lab biologists try to make them certain!). For\n",
    "instance, you might do a dinucleotide priming experiment and discover\n",
    "that the start of mRNA transcript starts at one of two sites. This\n",
    "is very useful information, but the complication comes in how to\n",
    "represent this as a position. To help us deal with this, we have\n",
    "the concept of fuzzy positions. Basically there are several types\n",
    "of fuzzy positions, so we have five classes do deal with them:\n",
    "\n",
    "* **ExactPosition** - As its name suggests, this class represents a position which is specified as exact along the sequence. This is represented as just a number, and you can get the position by looking at the position attribute of the object.\n",
    "\n",
    "* **BeforePosition** - This class represents a fuzzy position\n",
    "  that occurs prior to some specified site. In GenBank/EMBL notation,\n",
    "  this is represented as something like \\<13, signifying that\n",
    "  the real position is located somewhere less than 13. To get\n",
    "  the specified upper boundary, look at the position\n",
    "  attribute of the object.\n",
    "\n",
    "* **AfterPosition** - Contrary to BeforePosition, this\n",
    "  class represents a position that occurs after some specified site.\n",
    "  This is represented in GenBank as \\>13, and like\n",
    "  BeforePosition, you get the boundary number by looking\n",
    "  at the position attribute of the object.\n",
    "\n",
    "* **WithinPosition** - Occasionally used for GenBank/EMBL locations,\n",
    "  this class models a position which occurs somewhere between two\n",
    "  specified nucleotides. In GenBank/EMBL notation, this would be\n",
    "  represented as (1.5), to represent that the position is somewhere\n",
    "  within the range 1 to 5. To get the information in this class you\n",
    "  have to look at two attributes. The position attribute\n",
    "  specifies the lower boundary of the range we are looking at, so in\n",
    "  our example case this would be one. The extension attribute\n",
    "  specifies the range to the higher boundary, so in this case it\n",
    "  would be 4. So object.position is the lower boundary and\n",
    "  object.position + object.extension is the upper boundary.\n",
    "\n",
    "* **OneOfPosition** - Occasionally used for GenBank/EMBL locations,\n",
    "  this class deals with a position where several possible values exist,\n",
    "  for instance you could use this if the start codon was unclear and\n",
    "  there where two candidates for the start of the gene. Alternatively,\n",
    "  that might be handled explicitly as two related gene features.\n",
    "\n",
    "* **UnknownPosition** - This class deals with a position of unknown\n",
    "  location. This is not used in GenBank/EMBL, but corresponds to the `?'\n",
    "  feature coordinate used in UniProt.\n",
    "\n",
    "Here's an example where we create a location with fuzzy end points:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "start_pos = SeqFeature.AfterPosition(5)\n",
    "end_pos = SeqFeature.BetweenPosition(9, left=8, right=9)\n",
    "my_location = SeqFeature.FeatureLocation(start_pos, end_pos)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that the details of some of the fuzzy-locations changed in Biopython 1.59,\n",
    "in particular for BetweenPosition and WithinPosition you must now make it explicit\n",
    "which integer position should be used for slicing etc. For a start position this\n",
    "is generally the lower (left) value, while for an end position this would generally\n",
    "be the higher (right) value.\n",
    "\n",
    "If you print out a FeatureLocation object, you can get a nice representation of the information:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[>5:(8^9)]\n"
     ]
    }
   ],
   "source": [
    "print(my_location)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can access the fuzzy start and end positions using the start and end attributes of the location:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      ">5\n",
      ">5\n",
      "(8^9)\n",
      "(8^9)\n"
     ]
    }
   ],
   "source": [
    "print(my_location.start)\n",
    "print(my_location.start)\n",
    "print(my_location.end)\n",
    "print(my_location.end)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you don't want to deal with fuzzy positions and just want numbers,\n",
    "they are actually subclasses of integers so should work like integers:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n",
      "9\n"
     ]
    }
   ],
   "source": [
    "print(int(my_location.start))\n",
    "print(int(my_location.end))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "For compatibility with older versions of Biopython you can ask for the\n",
    "\\verb|nofuzzy_start| and \\verb|nofuzzy_end| attributes of the location\n",
    "which are plain integers:\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n",
      "9\n"
     ]
    }
   ],
   "source": [
    "print(my_location.nofuzzy_start)\n",
    "print(my_location.nofuzzy_end)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice that this just gives you back the position attributes of the fuzzy locations.\n",
    "\n",
    "Similarly, to make it easy to create a position without worrying about fuzzy positions, you can just pass in numbers to the \\verb|FeaturePosition| constructors, and you'll get back out \\verb|ExactPosition| objects:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[5:9]\n",
      "5\n",
      "5\n",
      "5\n"
     ]
    }
   ],
   "source": [
    "exact_location = SeqFeature.FeatureLocation(5, 9)\n",
    "print(exact_location)\n",
    "print(exact_location.start)\n",
    "print(int(exact_location.start))\n",
    "print(exact_location.nofuzzy_start)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That is most of the nitty gritty about dealing with fuzzy positions in Biopython.\n",
    "It has been designed so that dealing with fuzziness is not that much more\n",
    "complicated than dealing with exact positions, and hopefully you find that true!\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Location testing"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can use the Python keyword in with a SeqFeature or location\n",
    "object to see if the base/residue for a parent coordinate is within the\n",
    "feature/location or not.\n",
    "\n",
    "For example, suppose you have a SNP of interest and you want to know which\n",
    "features this SNP is within, and lets suppose this SNP is at index 4350\n",
    "(Python counting!). Here is a simple brute force solution where we just\n",
    "check all the features one by one in a loop:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "source ['taxon:229193']\n",
      "gene ['GeneID:2767712']\n",
      "CDS ['GI:45478716', 'GeneID:2767712']\n"
     ]
    }
   ],
   "source": [
    "my_snp = 4350\n",
    "record = SeqIO.read(\"data/NC_005816.gb\", \"genbank\")\n",
    "for feature in record.features:\n",
    "   if my_snp in feature:\n",
    "        print(\"%s %s\" % (feature.type, feature.qualifiers.get('db_xref')))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that gene and CDS features from GenBank or EMBL files defined with joins\n",
    "are the union of the exons -- they do not cover any introns.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Sequence described by a feature or location"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A SeqFeature or location object doesn't directly contain a sequence, instead the location describes how to get this from the parent sequence. For example consider a (short) gene sequence with location 5:18 on the reverse strand, which in GenBank/EMBL notation using 1-based counting would be complement(6..18), like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "example_parent = Seq(\"ACCGAGACGGCAAAGGCTAGCATAGGTATGAGACTTCCTTCCTGCCAGTGCTGAGGAACTGGGAGCCTAC\")\n",
    "example_feature = SeqFeature.SeqFeature(FeatureLocation(5, 18), type=\"gene\", strand=-1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You could take the parent sequence, slice it to extract 5:18, and then take the reverse complement.\n",
    "If you are using Biopython 1.59 or later, the feature location's start and end are integer like so this works:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "AGCCTTTGCCGTC\n"
     ]
    }
   ],
   "source": [
    "feature_seq = example_parent[example_feature.location.start:example_feature.location.end].reverse_complement()\n",
    "print(feature_seq)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is a simple example so this isn't too bad -- however once you have to deal with compound features (joins) this is rather messy. Instead, the SeqFeature object has an extract method to take care of all this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "AGCCTTTGCCGTC\n"
     ]
    }
   ],
   "source": [
    "feature_seq = example_feature.extract(example_parent)\n",
    "print(feature_seq)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The length of a SeqFeature or location matches\n",
    "that of the region of sequence it describes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "AGCCTTTGCCGTC\n",
      "13\n",
      "13\n",
      "13\n"
     ]
    }
   ],
   "source": [
    "print(example_feature.extract(example_parent))\n",
    "print(len(example_feature.extract(example_parent)))\n",
    "print(len(example_feature))\n",
    "print(len(example_feature.location))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For simple FeatureLocation objects the length is just the difference between the start and end positions. However, for a CompoundLocation the length is the sum of the constituent regions."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## References"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Another common annotation related to a sequence is a reference to a journal or other published work dealing with the sequence. We have a fairly simple way of representing a Reference in Biopython -- we have a Bio.SeqFeature.Reference class that stores the relevant information about a reference as attributes of an object.\n",
    "\n",
    "The attributes include things that you would expect to see in a reference like journal, title and authors. Additionally, it also can hold the medline_id and pubmed_id and a comment about the reference. These are all accessed simply as attributes of the object.\n",
    "\n",
    "A reference also has a location object so that it can specify a particular location on the sequence that the reference refers to. For instance, you might have a journal that is dealing with a particular gene located on a BAC, and want to specify that it only refers to this position exactly. The location is a potentially fuzzy location.\n",
    "\n",
    "Any reference objects are stored as a list in the SeqRecord object's annotations dictionary under the key 'references'.\n",
    "That's all there is too it. References are meant to be easy to deal with, and hopefully general enough to cover lots of usage cases."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The format method"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The format method of the SeqRecord class gives a string\n",
    "containing your record formatted using one of the output file formats\n",
    "supported by Bio.SeqIO, such as FASTA:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      ">gi|14150838|gb|AAK54648.1|AF376133_1 chalcone synthase [Cucumis sativus]\n",
      "MMYQQGCFAGGTVLRLAKDLAENNRGARVLVVCSEITAVTFRGPSETHLDSMVGQALFGD\n",
      "GAGAVIVGSDPDLSVERPLYELVWTGATLLPDSEGAIDGHLREVGLTFHLLKDVPGLISK\n",
      "NIEKSLKEAFTPLGISDWNSTFWIAHPGGPAILDQVEAKLGLKEEKMRATREVLSEYGNM\n",
      "SSAC\n",
      "\n"
     ]
    }
   ],
   "source": [
    "record = SeqRecord(Seq(\"MMYQQGCFAGGTVLRLAKDLAENNRGARVLVVCSEITAVTFRGPSETHLDSMVGQALFGD\" \\\n",
    "                      +\"GAGAVIVGSDPDLSVERPLYELVWTGATLLPDSEGAIDGHLREVGLTFHLLKDVPGLISK\" \\\n",
    "                      +\"NIEKSLKEAFTPLGISDWNSTFWIAHPGGPAILDQVEAKLGLKEEKMRATREVLSEYGNM\" \\\n",
    "                      +\"SSAC\", generic_protein),\n",
    "                   id=\"gi|14150838|gb|AAK54648.1|AF376133_1\",\n",
    "                   description=\"chalcone synthase [Cucumis sativus]\")\n",
    "print(record.format(\"fasta\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This format method takes a single mandatory argument, a lower case string which is\n",
    "supported by Bio.SeqIO as an output format.\n",
    "However, some of the file formats Bio.SeqIO can write to _require_ more than\n",
    "one record (typically the case for multiple sequence alignment formats), and thus won't\n",
    "work via this format method."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Slicing a SeqRecord"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can slice a SeqRecord, to give you a new SeqRecord covering just\n",
    "part of the sequence. What is important\n",
    "here is that any per-letter annotations are also sliced, and any features which fall\n",
    "completely within the new sequence are preserved (with their locations adjusted).\n",
    "\n",
    "For example, taking the same GenBank file used earlier:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ID: NC_005816.1\n",
      "Name: NC_005816\n",
      "Description: Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.\n",
      "Database cross-references: Project:58037\n",
      "Number of features: 41\n",
      "/taxonomy=['Bacteria', 'Proteobacteria', 'Gammaproteobacteria', 'Enterobacteriales', 'Enterobacteriaceae', 'Yersinia']\n",
      "/comment=PROVISIONAL REFSEQ: This record has not yet been subject to final\n",
      "NCBI review. The reference sequence was derived from AE017046.\n",
      "COMPLETENESS: full length.\n",
      "/accessions=['NC_005816']\n",
      "/organism=Yersinia pestis biovar Microtus str. 91001\n",
      "/sequence_version=1\n",
      "/source=Yersinia pestis biovar Microtus str. 91001\n",
      "/data_file_division=BCT\n",
      "/keywords=['']\n",
      "/date=21-JUL-2008\n",
      "/gi=45478711\n",
      "/references=[Reference(title='Genetics of metabolic variations between Yersinia pestis biovars and the proposal of a new biovar, microtus', ...), Reference(title='Complete genome sequence of Yersinia pestis strain 91001, an isolate avirulent to humans', ...), Reference(title='Direct Submission', ...), Reference(title='Direct Submission', ...)]\n",
      "Seq('TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGG...CTG', IUPACAmbiguousDNA())\n",
      "9609\n",
      "41\n"
     ]
    }
   ],
   "source": [
    "record = SeqIO.read(\"data/NC_005816.gb\", \"genbank\")\n",
    "print(record)\n",
    "print(len(record))\n",
    "print(len(record.features))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For this example we're going to focus in on the pim gene, YP_pPCP05.\n",
    "If you have a look at the GenBank file directly you'll find this gene/CDS has\n",
    "location string 4343..4780, or in Python counting 4342:4780.\n",
    "From looking at the file you can work out that these are the twelfth and\n",
    "thirteenth entries in the file, so in Python zero-based counting they are\n",
    "entries 11 and 12 in the features list:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "type: gene\n",
      "location: [4342:4780](+)\n",
      "qualifiers:\n",
      "    Key: db_xref, Value: ['GeneID:2767712']\n",
      "    Key: gene, Value: ['pim']\n",
      "    Key: locus_tag, Value: ['YP_pPCP05']\n",
      "\n",
      "type: CDS\n",
      "location: [4342:4780](+)\n",
      "qualifiers:\n",
      "    Key: codon_start, Value: ['1']\n",
      "    Key: db_xref, Value: ['GI:45478716', 'GeneID:2767712']\n",
      "    Key: gene, Value: ['pim']\n",
      "    Key: locus_tag, Value: ['YP_pPCP05']\n",
      "    Key: note, Value: ['similar to many previously sequenced pesticin immunity protein entries of Yersinia pestis plasmid pPCP, e.g. gi| 16082683|,ref|NP_395230.1| (NC_003132) , gi|1200166|emb|CAA90861.1| (Z54145 ) , gi|1488655| emb|CAA63439.1| (X92856) , gi|2996219|gb|AAC62543.1| (AF053945) , and gi|5763814|emb|CAB531 67.1| (AL109969)']\n",
      "    Key: product, Value: ['pesticin immunity protein']\n",
      "    Key: protein_id, Value: ['NP_995571.1']\n",
      "    Key: transl_table, Value: ['11']\n",
      "    Key: translation, Value: ['MGGGMISKLFCLALIFLSSSGLAEKNTYTAKDILQNLELNTFGNSLSHGIYGKQTTFKQTEFTNIKSNTKKHIALINKDNSWMISLKILGIKRDEYTVCFEDFSLIRPPTYVAIHPLLIKKVKSGNFIVVKEIKKSIPGCTVYYH']\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(record.features[20])\n",
    "print(record.features[21])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's slice this parent record from 4300 to 4800 (enough to include the pim\n",
    "gene/CDS), and see how many features we get:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ID: NC_005816.1\n",
      "Name: NC_005816\n",
      "Description: Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.\n",
      "Number of features: 2\n",
      "Seq('ATAAATAGATTATTCCAAATAATTTATTTATGTAAGAACAGGATGGGAGGGGGA...TTA', IUPACAmbiguousDNA())\n",
      "ID: NC_005816.1\n",
      "Name: NC_005816\n",
      "Description: Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.\n",
      "Number of features: 2\n",
      "Seq('ATAAATAGATTATTCCAAATAATTTATTTATGTAAGAACAGGATGGGAGGGGGA...TTA', IUPACAmbiguousDNA())\n",
      "500\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "sub_record = record[4300:4800]\n",
    "print(sub_record)\n",
    "sub_record\n",
    "print(sub_record)\n",
    "print(len(sub_record))\n",
    "print(len(sub_record.features))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Our sub-record just has two features, the gene and CDS entries for YP_pPCP05:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "type: gene\n",
      "location: [42:480](+)\n",
      "qualifiers:\n",
      "    Key: db_xref, Value: ['GeneID:2767712']\n",
      "    Key: gene, Value: ['pim']\n",
      "    Key: locus_tag, Value: ['YP_pPCP05']\n",
      "\n",
      "type: CDS\n",
      "location: [42:480](+)\n",
      "qualifiers:\n",
      "    Key: codon_start, Value: ['1']\n",
      "    Key: db_xref, Value: ['GI:45478716', 'GeneID:2767712']\n",
      "    Key: gene, Value: ['pim']\n",
      "    Key: locus_tag, Value: ['YP_pPCP05']\n",
      "    Key: note, Value: ['similar to many previously sequenced pesticin immunity protein entries of Yersinia pestis plasmid pPCP, e.g. gi| 16082683|,ref|NP_395230.1| (NC_003132) , gi|1200166|emb|CAA90861.1| (Z54145 ) , gi|1488655| emb|CAA63439.1| (X92856) , gi|2996219|gb|AAC62543.1| (AF053945) , and gi|5763814|emb|CAB531 67.1| (AL109969)']\n",
      "    Key: product, Value: ['pesticin immunity protein']\n",
      "    Key: protein_id, Value: ['NP_995571.1']\n",
      "    Key: transl_table, Value: ['11']\n",
      "    Key: translation, Value: ['MGGGMISKLFCLALIFLSSSGLAEKNTYTAKDILQNLELNTFGNSLSHGIYGKQTTFKQTEFTNIKSNTKKHIALINKDNSWMISLKILGIKRDEYTVCFEDFSLIRPPTYVAIHPLLIKKVKSGNFIVVKEIKKSIPGCTVYYH']\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(sub_record.features[0])\n",
    "print(sub_record.features[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice that their locations have been adjusted to reflect the new parent sequence!\n",
    "\n",
    "While Biopython has done something sensible and hopefully intuitive with the features\n",
    "(and any per-letter annotation), for the other annotation it is impossible to know if\n",
    "this still applies to the sub-sequence or not. To avoid guessing, the annotations\n",
    "and dbxrefs are omitted from the sub-record, and it is up to you to transfer\n",
    "any relevant information as appropriate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{}\n",
      "[]\n"
     ]
    }
   ],
   "source": [
    "print(sub_record.annotations)\n",
    "print(sub_record.dbxrefs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same point could be made about the record id, name\n",
    "and description, but for practicality these are preserved:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "NC_005816.1\n",
      "NC_005816\n",
      "Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.\n"
     ]
    }
   ],
   "source": [
    "print(sub_record.id)\n",
    "print(sub_record.name)\n",
    "print(sub_record.description)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This illustrates the problem nicely though, our new sub-record is\n",
    "_not_ the complete sequence of the plasmid, so the description is wrong!\n",
    "Let's fix this and then view the sub-record as a reduced GenBank file using\n",
    "the format method described above:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "LOCUS       NC_005816                500 bp    DNA              UNK 01-JAN-1980\n",
      "DEFINITION  Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, partial.\n",
      "ACCESSION   NC_005816\n",
      "VERSION     NC_005816.1\n",
      "KEYWORDS    .\n",
      "SOURCE      .\n",
      "  ORGANISM  .\n",
      "            .\n",
      "FEATURES             Location/Qualifiers\n",
      "     gene            43..480\n",
      "                     /db_xref=\"GeneID:2767712\"\n",
      "                     /gene=\"pim\"\n",
      "                     /locus_tag=\"YP_pPCP05\"\n",
      "     CDS             43..480\n",
      "                     /codon_start=1\n",
      "                     /db_xref=\"GI:45478716\"\n",
      "                     /db_xref=\"GeneID:2767712\"\n",
      "                     /gene=\"pim\"\n",
      "                     /locus_tag=\"YP_pPCP05\"\n",
      "                     /note=\"similar to many previously sequenced pesticin\n",
      "                     immunity protein entries of Yersinia pestis plasmid pPCP,\n",
      "                     e.g. gi| 16082683|,ref|NP_395230.1| (NC_003132) ,\n",
      "                     gi|1200166|emb|CAA90861.1| (Z54145 ) , gi|1488655|\n",
      "                     emb|CAA63439.1| (X92856) , gi|2996219|gb|AAC62543.1|\n",
      "                     (AF053945) , and gi|5763814|emb|CAB531 67.1| (AL109969)\"\n",
      "                     /product=\"pesticin immunity protein\"\n",
      "                     /protein_id=\"NP_995571.1\"\n",
      "                     /transl_table=11\n",
      "                     /translation=\"MGGGMISKLFCLALIFLSSSGLAEKNTYTAKDILQNLELNTFGNS\n",
      "                     LSHGIYGKQTTFKQTEFTNIKSNTKKHIALINKDNSWMISLKILGIKRDEYTVCFEDFS\n",
      "                     LIRPPTYVAIHPLLIKKVKSGNFIVVKEIKKSIPGCTVYYH\"\n",
      "ORIGIN\n",
      "        1 ataaatagat tattccaaat aatttattta tgtaagaaca ggatgggagg gggaatgatc\n",
      "       61 tcaaagttat tttgcttggc tctcatattt ttatcatcaa gtggccttgc agaaaaaaac\n",
      "      121 acatatacag caaaagacat cttgcaaaac ctagaattaa atacctttgg caattcattg\n",
      "      181 tctcatggca tctatgggaa acagacaacc ttcaagcaaa ccgagtttac aaatattaaa\n",
      "      241 agcaacacca aaaaacacat tgcacttatc aataaagaca actcatggat gatatcatta\n",
      "      301 aaaatactag gaattaagag agatgagtat actgtctgtt ttgaagattt ctctctaata\n",
      "      361 agaccgccaa catatgtagc catacatcct ctacttataa aaaaagtaaa atctggaaac\n",
      "      421 tttatagtag tgaaagaaat aaagaaatct atccctggtt gcactgtata ttatcattaa\n",
      "      481 tagcaagccc ctcattatta\n",
      "//\n",
      "\n"
     ]
    }
   ],
   "source": [
    "sub_record.description = \"Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, partial.\"\n",
    "print(sub_record.format(\"genbank\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Adding SeqRecord objects"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can add SeqRecord objects together, giving a new SeqRecord.\n",
    "What is important here is that any common\n",
    "per-letter annotations are also added, all the features are preserved (with their\n",
    "locations adjusted), and any other common annotation is also kept (like the id, name\n",
    "and description).\n",
    "\n",
    "For an example with per-letter annotation, we'll use the first record in a\n",
    "FASTQ file."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "25\n",
      "CCCTTCTTGTCTTCAGCGTTTCTCC\n",
      "[26, 26, 18, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 22, 26, 26, 26, 26, 26, 26, 26, 23, 23]\n"
     ]
    }
   ],
   "source": [
    "record = next(SeqIO.parse(\"data/example.fastq\", \"fastq\"))\n",
    "print(len(record))\n",
    "print(record.seq)\n",
    "print(record.letter_annotations[\"phred_quality\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's suppose this was Roche 454 data, and that from other information\n",
    "you think the TTT should be only TT. We can make a new edited\n",
    "record by first slicing the SeqRecord before and after the 'extra'\n",
    "third T:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CCCTTCTTGTCTTCAGCGTT\n",
      "[26, 26, 18, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 22, 26, 26, 26, 26]\n",
      "CTCC\n",
      "[26, 26, 23, 23]\n"
     ]
    }
   ],
   "source": [
    "left = record[:20]\n",
    "print(left.seq)\n",
    "print(left.letter_annotations[\"phred_quality\"])\n",
    "right = record[21:]\n",
    "print(right.seq)\n",
    "print(right.letter_annotations[\"phred_quality\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now add the two parts together:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "24\n",
      "CCCTTCTTGTCTTCAGCGTTCTCC\n",
      "[26, 26, 18, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 22, 26, 26, 26, 26, 26, 26, 23, 23]\n"
     ]
    }
   ],
   "source": [
    "edited = left + right\n",
    "print(len(edited))\n",
    "print(edited.seq)\n",
    "print(edited.letter_annotations[\"phred_quality\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Easy and intuitive? We hope so! You can make this shorter with just:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "edited = record[:20] + record[21:]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, for an example with features, we'll use a GenBank file.\n",
    "Suppose you have a circular genome:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ID: NC_005816.1\n",
      "Name: NC_005816\n",
      "Description: Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.\n",
      "Database cross-references: Project:58037\n",
      "Number of features: 41\n",
      "/taxonomy=['Bacteria', 'Proteobacteria', 'Gammaproteobacteria', 'Enterobacteriales', 'Enterobacteriaceae', 'Yersinia']\n",
      "/comment=PROVISIONAL REFSEQ: This record has not yet been subject to final\n",
      "NCBI review. The reference sequence was derived from AE017046.\n",
      "COMPLETENESS: full length.\n",
      "/accessions=['NC_005816']\n",
      "/organism=Yersinia pestis biovar Microtus str. 91001\n",
      "/sequence_version=1\n",
      "/source=Yersinia pestis biovar Microtus str. 91001\n",
      "/data_file_division=BCT\n",
      "/keywords=['']\n",
      "/date=21-JUL-2008\n",
      "/gi=45478711\n",
      "/references=[Reference(title='Genetics of metabolic variations between Yersinia pestis biovars and the proposal of a new biovar, microtus', ...), Reference(title='Complete genome sequence of Yersinia pestis strain 91001, an isolate avirulent to humans', ...), Reference(title='Direct Submission', ...), Reference(title='Direct Submission', ...)]\n",
      "Seq('TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGG...CTG', IUPACAmbiguousDNA())\n",
      "9609\n",
      "41\n",
      "['Project:58037']\n",
      "dict_keys(['taxonomy', 'comment', 'accessions', 'organism', 'sequence_version', 'source', 'data_file_division', 'keywords', 'date', 'gi', 'references'])\n"
     ]
    }
   ],
   "source": [
    "record = SeqIO.read(\"data/NC_005816.gb\", \"genbank\")\n",
    "print(record)\n",
    "print(len(record))\n",
    "print(len(record.features))\n",
    "print(record.dbxrefs)\n",
    "print(record.annotations.keys())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can shift the origin like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ID: NC_005816.1\n",
      "Name: NC_005816\n",
      "Description: Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.\n",
      "Number of features: 40\n",
      "Seq('GATACGCAGTCATATTTTTTACACAATTCTCTAATCCCGACAAGGTCGTAGGTC...GGA', IUPACAmbiguousDNA())\n",
      "9609\n"
     ]
    }
   ],
   "source": [
    "shifted = record[2000:] + record[:2000]\n",
    "print(shifted)\n",
    "print(len(shifted))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that this isn't perfect in that some annotation like the database cross references\n",
    "and one of the features (the source feature) have been lost:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "40\n",
      "[]\n",
      "dict_keys([])\n"
     ]
    }
   ],
   "source": [
    "print(len(shifted.features))\n",
    "print(shifted.dbxrefs)\n",
    "print(shifted.annotations.keys())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is because the SeqRecord slicing step is cautious in what annotation\n",
    "it preserves (erroneously propagating annotation can cause major problems). If\n",
    "you want to keep the database cross references or the annotations dictionary,\n",
    "this must be done explicitly:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Project:58037']\n",
      "dict_keys(['accessions', 'source', 'data_file_division', 'comment', 'gi', 'references', 'taxonomy', 'organism', 'sequence_version', 'keywords', 'date'])\n"
     ]
    }
   ],
   "source": [
    "shifted.dbxrefs = record.dbxrefs[:]\n",
    "shifted.annotations = record.annotations.copy()\n",
    "print(shifted.dbxrefs)\n",
    "print(shifted.annotations.keys())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Also note that in an example like this, you should probably change the record\n",
    "identifiers since the NCBI references refer to the _original_ unmodified\n",
    "sequence."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reverse-complementing SeqRecord objects"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One of the new features in Biopython 1.57 was the SeqRecord object's\n",
    "reverse_complement method. This tries to balance easy of use with worries\n",
    "about what to do with the annotation in the reverse complemented record.\n",
    "\n",
    "For the sequence, this uses the Seq object's reverse complement method. Any\n",
    "features are transferred with the location and strand recalculated. Likewise\n",
    "any per-letter-annotation is also copied but reversed (which makes sense for\n",
    "typical examples like quality scores). However, transfer of most annotation\n",
    "is problematical.\n",
    "\n",
    "For instance, if the record ID was an accession, that accession should not really\n",
    "apply to the reverse complemented sequence, and transferring the identifier by\n",
    "default could easily cause subtle data corruption in downstream analysis.\n",
    "Therefore by default, the SeqRecord's id, name, description, annotations\n",
    "and database cross references are all _not_ transferred by default.\n",
    "\n",
    "The SeqRecord object's reverse_complement method takes a number\n",
    "of optional arguments corresponding to properties of the record. Setting these\n",
    "arguments to True means copy the old values, while False means\n",
    "drop the old values and use the default value. You can alternatively provide\n",
    "the new desired value instead.\n",
    "\n",
    "Consider this example record:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "NC_005816.1 9609 41 1 11\n"
     ]
    }
   ],
   "source": [
    "record = SeqIO.read(\"data/NC_005816.gb\", \"genbank\")\n",
    "print(\"%s %i %i %i %i\" % (record.id, len(record), len(record.features), len(record.dbxrefs), len(record.annotations)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here we take the reverse complement and specify a new identifier - but notice\n",
    "how most of the annotation is dropped (but not the features):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "TESTING 9609 41 0 0\n"
     ]
    }
   ],
   "source": [
    "rc = record.reverse_complement(id=\"TESTING\")\n",
    "print(\"%s %i %i %i %i\" % (rc.id, len(rc), len(rc.features), len(rc.dbxrefs), len(rc.annotations)))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
